Skip to content

[Search][Query Rules UI] Test in console and delete ruleset from details page #221350

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
May 28, 2025

Conversation

JoseLuisGJ
Copy link
Contributor

@JoseLuisGJ JoseLuisGJ commented May 23, 2025

Summary

Adding Test in Console and Delete from the Ruleset details page:

CleanShot.2025-05-23.at.12.20.12.mp4

Test in Console example populating data from the ruleset selected:

CleanShot 2025-05-23 at 12 18 35@2x

Checklist

Check the PR satisfies following conditions.

Reviewers should verify this PR satisfies this list as well.

  • Any text added follows EUI's writing guidelines, uses sentence case text and includes i18n support
  • Documentation was added for features that require explanation or tutorials
  • Unit or functional tests were updated or added to match the most common scenarios
  • If a plugin configuration key changed, check if it needs to be allowlisted in the cloud and added to the docker list
  • This was checked for breaking HTTP API changes, and any breaking changes have been approved by the breaking-change committee. The release_note:breaking label should be applied in these situations.
  • Flaky Test Runner was used on any tests changed
  • The PR description includes the appropriate Release Notes section, and the correct release_note:* label is applied per the guidelines

Identify risks

Does this PR introduce any risks? For example, consider risks like hard to test bugs, performance regression, potential of data loss.

Describe the risk, its severity, and mitigation for each identified risk. Invite stakeholders and evaluate how to proceed before merging.

@JoseLuisGJ JoseLuisGJ changed the title Test-ruleset-detailspage [Search][Query Rules UI] Test in console and delete ruleset from details page May 23, 2025
@JoseLuisGJ JoseLuisGJ self-assigned this May 23, 2025
@JoseLuisGJ JoseLuisGJ added release_note:skip Skip the PR/issue when compiling release notes Team:Search backport:version Backport to applied version labels v9.1.0 v8.19.0 labels May 23, 2025
@JoseLuisGJ JoseLuisGJ marked this pull request as ready for review May 23, 2025 10:25
@JoseLuisGJ JoseLuisGJ requested a review from a team as a code owner May 23, 2025 10:25
@JoseLuisGJ
Copy link
Contributor Author

@elasticmachine merge upstream

Copy link
Contributor

@Samiul-TheSoccerFan Samiul-TheSoccerFan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, left some comments and one performance improvement suggestion

Comment on lines 27 to 73
// Loop through all actions children to gather unique _index values
const indices: Set<string> = new Set();
if (queryRulesetData?.rules) {
for (const rule of queryRulesetData.rules) {
if (rule.actions?.docs) {
for (const doc of rule.actions.docs) {
if (doc._index) {
indices.add(doc._index);
}
}
}
}
}

// Use the found indices or default to 'my_index'
const indecesRuleset = indices.size > 0 ? Array.from(indices).join(',') : 'my_index';

// Extract match criteria metadata and values from the ruleset
const criteriaData = [];
if (queryRulesetData?.rules) {
for (const rule of queryRulesetData.rules) {
if (rule.criteria) {
// Handle both single criterion and array of criteria
const criteriaArray = Array.isArray(rule.criteria) ? rule.criteria : [rule.criteria];
for (const criterion of criteriaArray) {
if (
criterion.values &&
typeof criterion.values === 'object' &&
!Array.isArray(criterion.values)
) {
// Handle nested values inside criterion.values
Object.entries(criterion.values).forEach(([key, value]) => {
criteriaData.push({
metadata: key,
values: value,
});
});
} else {
criteriaData.push({
metadata: criterion.metadata || null,
values: criterion.values || null,
});
}
}
}
}
}
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think we can make it a little performant by using useMemo to make sure we do not do all of these processing for each render.

const { indices, matchCriteria } = useMemo(() => {
    const indicesSet = new Set<string>();
    const criteriaData = [];

    for (const rule of queryRulesetData?.rules ?? []) {
      // Collect indices
      rule.actions?.docs?.forEach((doc) => {
        if (doc._index) indicesSet.add(doc._index);
      });

      // Collect criteria
      const criteriaArray = Array.isArray(rule.criteria)
        ? rule.criteria
        : rule.criteria
        ? [rule.criteria]
        : [];

      for (const criterion of criteriaArray) {
        if (criterion.values && typeof criterion.values === 'object' && !Array.isArray(criterion.values)) {
          Object.entries(criterion.values).forEach(([key, value]) => {
            criteriaData.push({ metadata: key, values: value });
          });
        } else {
          criteriaData.push({
            metadata: criterion.metadata || null,
            values: criterion.values || null,
          });
        }
      }
    }

    const matchCriteria = criteriaData.reduce<Record<string, any>>((acc, { metadata, values }) => {
      if (metadata && values !== undefined) acc[metadata] = values;
      return acc;
    }, {});

    return {
      indices: indicesSet.size > 0 ? Array.from(indicesSet).join(',') : 'my_index',
      matchCriteria: Object.keys(matchCriteria).length > 0
        ? JSON.stringify(matchCriteria, null, 2).split('\n').join('\n         ')
        : `{\n         "user_query": "pugs"\n    }`,
    };
  }, [queryRulesetData]);

  const query = dedent`
    # Query Rules Retriever Example
    # https://www.elastic.co/docs/reference/elasticsearch/rest-apis/retrievers#rule-retriever
    GET ${indices}/_search
    {
      "retriever": {
        "rule": {
          "match_criteria": ${matchCriteria},
          "ruleset_ids": [
            "${rulesetId}" // An array of one or more unique query ruleset IDs
          ],
          "retriever": {
            "standard": {
              "query": {
                "query_string": {
                  "query": "pugs"
                }
              }
            }
          }
        }
      }
    }
  `;

This is a probable workaround and it might be missing some typing and comments too.

Copy link
Contributor Author

@JoseLuisGJ JoseLuisGJ May 27, 2025

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks @Samiul-TheSoccerFan . I had to tweak a bit your suggestion to avoid some TS issues, let me know if it already works for you:

const { indices, matchCriteria } = useMemo((): { indices: string; matchCriteria: string } => {
  const indicesSet = new Set<string>();
  const criteriaData = [];

  for (const rule of queryRulesetData?.rules ?? []) {
    // Collect indices
    rule.actions?.docs?.forEach((doc) => {
      if (doc._index) indicesSet.add(doc._index);
    });

    // Collect criteria
    const criteriaArray = Array.isArray(rule.criteria)
      ? rule.criteria
      : rule.criteria
      ? [rule.criteria]
      : [];

    for (const criterion of criteriaArray) {
      if (
        criterion.values &&
        typeof criterion.values === 'object' &&
        !Array.isArray(criterion.values)
      ) {
        Object.entries(criterion.values).forEach(([key, value]) => {
          criteriaData.push({ metadata: key, values: value });
        });
      } else {
        criteriaData.push({
          metadata: criterion.metadata || null,
          values: criterion.values || null,
        });
      }
    }
  }

  const reducedCriteria = criteriaData.reduce<Record<string, any>>(
    (acc, { metadata, values }) => {
      if (metadata && values !== undefined) acc[metadata] = values;
      return acc;
    },
    {}
  );

  return {
    indices: indicesSet.size > 0 ? Array.from(indicesSet).join(',') : 'my_index',
    matchCriteria:
      Object.keys(reducedCriteria).length > 0
        ? JSON.stringify(reducedCriteria, null, 2).split('\n').join('\n         ')
        : `{\n         "user_query": "pugs"\n    }`,
  };
}, [queryRulesetData]);
  const TEST_QUERY_RULESET_API_SNIPPET = dedent`
    # Query Rules Retriever Example
    # https://www.elastic.co/docs/reference/elasticsearch/rest-apis/retrievers#rule-retriever
    GET ${indices}/_search
    {
      "retriever": {
        "rule": {
          "match_criteria": ${matchCriteria},
          "ruleset_ids": [
            "${rulesetId}" // An array of one or more unique query ruleset IDs
          ],
          "retriever": {
            "standard": {
              "query": {
                "query_string": {
                  "query": "pugs"
                }
              }
            }
          }
        }
      }
    }
  `;

@elasticmachine
Copy link
Contributor

💚 Build Succeeded

Metrics [docs]

Async chunks

Total size of all lazy-loaded chunks that will be downloaded as the user navigates the app

id before after diff
searchQueryRules 45.6KB 47.1KB +1.5KB

History

cc @JoseLuisGJ

Copy link
Contributor

@Samiul-TheSoccerFan Samiul-TheSoccerFan left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, thank you for adding the appropriate types.

@JoseLuisGJ JoseLuisGJ merged commit 661b96f into elastic:main May 28, 2025
10 checks passed
@kibanamachine
Copy link
Contributor

Starting backport for target branches: 8.19

https://github.com/elastic/kibana/actions/runs/15294014898

kibanamachine added a commit to kibanamachine/kibana that referenced this pull request May 28, 2025
…ils page (elastic#221350)

## Summary

Adding Test in Console and Delete from the Ruleset details page:

https://github.com/user-attachments/assets/e9db3752-a2e9-4a28-adac-0716809884d6

Test in Console example populating data from the ruleset selected:

![CleanShot 2025-05-23 at 12 18
35@2x](https://github.com/user-attachments/assets/fc94c0e0-f412-4193-9662-9a23703fbfcd)

### Checklist

Check the PR satisfies following conditions.

Reviewers should verify this PR satisfies this list as well.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This was checked for breaking HTTP API changes, and any breaking
changes have been approved by the breaking-change committee. The
`release_note:breaking` label should be applied in these situations.
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] The PR description includes the appropriate Release Notes section,
and the correct `release_note:*` label is applied per the
[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

### Identify risks

Does this PR introduce any risks? For example, consider risks like hard
to test bugs, performance regression, potential of data loss.

Describe the risk, its severity, and mitigation for each identified
risk. Invite stakeholders and evaluate how to proceed before merging.

- [ ] [See some risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
- [ ] ...

---------

Co-authored-by: Elastic Machine <[email protected]>
Co-authored-by: kibanamachine <[email protected]>
(cherry picked from commit 661b96f)
@kibanamachine
Copy link
Contributor

💚 All backports created successfully

Status Branch Result
8.19

Note: Successful backport PRs will be merged automatically after passing CI.

Questions ?

Please refer to the Backport tool documentation

kibanamachine added a commit that referenced this pull request May 28, 2025
…om details page (#221350) (#221726)

# Backport

This will backport the following commits from `main` to `8.19`:
- [[Search][Query Rules UI] Test in console and delete ruleset from
details page (#221350)](#221350)

<!--- Backport version: 9.6.6 -->

### Questions ?
Please refer to the [Backport tool
documentation](https://github.com/sorenlouv/backport)

<!--BACKPORT [{"author":{"name":"José Luis
González","email":"[email protected]"},"sourceCommit":{"committedDate":"2025-05-28T07:20:31Z","message":"[Search][Query
Rules UI] Test in console and delete ruleset from details page
(#221350)\n\n## Summary\n\nAdding Test in Console and Delete from the
Ruleset details
page:\n\n\n\nhttps://github.com/user-attachments/assets/e9db3752-a2e9-4a28-adac-0716809884d6\n\n\nTest
in Console example populating data from the ruleset
selected:\n\n![CleanShot 2025-05-23 at 12
18\n35@2x](https://github.com/user-attachments/assets/fc94c0e0-f412-4193-9662-9a23703fbfcd)\n\n\n\n###
Checklist\n\nCheck the PR satisfies following conditions. \n\nReviewers
should verify this PR satisfies this list as well.\n\n- [ ] Any text
added follows [EUI's
writing\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\nsentence case text and includes
[i18n\nsupport](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)\n-
[
]\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\nwas
added for features that require explanation or tutorials\n- [ ] [Unit or
functional\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\nwere
updated or added to match the most common scenarios\n- [ ] If a plugin
configuration key changed, check if it needs to be\nallowlisted in the
cloud and added to the
[docker\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\n-
[ ] This was checked for breaking HTTP API changes, and any
breaking\nchanges have been approved by the breaking-change committee.
The\n`release_note:breaking` label should be applied in these
situations.\n- [ ] [Flaky
Test\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\nused on any tests changed\n- [ ] The PR description includes the
appropriate Release Notes section,\nand the correct `release_note:*`
label is applied per
the\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\n\n###
Identify risks\n\nDoes this PR introduce any risks? For example,
consider risks like hard\nto test bugs, performance regression,
potential of data loss.\n\nDescribe the risk, its severity, and
mitigation for each identified\nrisk. Invite stakeholders and evaluate
how to proceed before merging.\n\n- [ ] [See some
risk\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\n-
[ ] ...\n\n---------\n\nCo-authored-by: Elastic Machine
<[email protected]>\nCo-authored-by: kibanamachine
<[email protected]>","sha":"661b96f71904783e02ec13c155062150e92f4139","branchLabelMapping":{"^v9.1.0$":"main","^v(\\d+).(\\d+).\\d+$":"$1.$2"}},"sourcePullRequest":{"labels":["release_note:skip","Team:Search","backport:version","v9.1.0","v8.19.0"],"title":"[Search][Query
Rules UI] Test in console and delete ruleset from details
page","number":221350,"url":"https://github.com/elastic/kibana/pull/221350","mergeCommit":{"message":"[Search][Query
Rules UI] Test in console and delete ruleset from details page
(#221350)\n\n## Summary\n\nAdding Test in Console and Delete from the
Ruleset details
page:\n\n\n\nhttps://github.com/user-attachments/assets/e9db3752-a2e9-4a28-adac-0716809884d6\n\n\nTest
in Console example populating data from the ruleset
selected:\n\n![CleanShot 2025-05-23 at 12
18\n35@2x](https://github.com/user-attachments/assets/fc94c0e0-f412-4193-9662-9a23703fbfcd)\n\n\n\n###
Checklist\n\nCheck the PR satisfies following conditions. \n\nReviewers
should verify this PR satisfies this list as well.\n\n- [ ] Any text
added follows [EUI's
writing\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\nsentence case text and includes
[i18n\nsupport](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)\n-
[
]\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\nwas
added for features that require explanation or tutorials\n- [ ] [Unit or
functional\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\nwere
updated or added to match the most common scenarios\n- [ ] If a plugin
configuration key changed, check if it needs to be\nallowlisted in the
cloud and added to the
[docker\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\n-
[ ] This was checked for breaking HTTP API changes, and any
breaking\nchanges have been approved by the breaking-change committee.
The\n`release_note:breaking` label should be applied in these
situations.\n- [ ] [Flaky
Test\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\nused on any tests changed\n- [ ] The PR description includes the
appropriate Release Notes section,\nand the correct `release_note:*`
label is applied per
the\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\n\n###
Identify risks\n\nDoes this PR introduce any risks? For example,
consider risks like hard\nto test bugs, performance regression,
potential of data loss.\n\nDescribe the risk, its severity, and
mitigation for each identified\nrisk. Invite stakeholders and evaluate
how to proceed before merging.\n\n- [ ] [See some
risk\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\n-
[ ] ...\n\n---------\n\nCo-authored-by: Elastic Machine
<[email protected]>\nCo-authored-by: kibanamachine
<[email protected]>","sha":"661b96f71904783e02ec13c155062150e92f4139"}},"sourceBranch":"main","suggestedTargetBranches":["8.19"],"targetPullRequestStates":[{"branch":"main","label":"v9.1.0","branchLabelMappingKey":"^v9.1.0$","isSourceBranch":true,"state":"MERGED","url":"https://github.com/elastic/kibana/pull/221350","number":221350,"mergeCommit":{"message":"[Search][Query
Rules UI] Test in console and delete ruleset from details page
(#221350)\n\n## Summary\n\nAdding Test in Console and Delete from the
Ruleset details
page:\n\n\n\nhttps://github.com/user-attachments/assets/e9db3752-a2e9-4a28-adac-0716809884d6\n\n\nTest
in Console example populating data from the ruleset
selected:\n\n![CleanShot 2025-05-23 at 12
18\n35@2x](https://github.com/user-attachments/assets/fc94c0e0-f412-4193-9662-9a23703fbfcd)\n\n\n\n###
Checklist\n\nCheck the PR satisfies following conditions. \n\nReviewers
should verify this PR satisfies this list as well.\n\n- [ ] Any text
added follows [EUI's
writing\nguidelines](https://elastic.github.io/eui/#/guidelines/writing),
uses\nsentence case text and includes
[i18n\nsupport](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)\n-
[
]\n[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)\nwas
added for features that require explanation or tutorials\n- [ ] [Unit or
functional\ntests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)\nwere
updated or added to match the most common scenarios\n- [ ] If a plugin
configuration key changed, check if it needs to be\nallowlisted in the
cloud and added to the
[docker\nlist](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)\n-
[ ] This was checked for breaking HTTP API changes, and any
breaking\nchanges have been approved by the breaking-change committee.
The\n`release_note:breaking` label should be applied in these
situations.\n- [ ] [Flaky
Test\nRunner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1)
was\nused on any tests changed\n- [ ] The PR description includes the
appropriate Release Notes section,\nand the correct `release_note:*`
label is applied per
the\n[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)\n\n###
Identify risks\n\nDoes this PR introduce any risks? For example,
consider risks like hard\nto test bugs, performance regression,
potential of data loss.\n\nDescribe the risk, its severity, and
mitigation for each identified\nrisk. Invite stakeholders and evaluate
how to proceed before merging.\n\n- [ ] [See some
risk\nexamples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)\n-
[ ] ...\n\n---------\n\nCo-authored-by: Elastic Machine
<[email protected]>\nCo-authored-by: kibanamachine
<[email protected]>","sha":"661b96f71904783e02ec13c155062150e92f4139"}},{"branch":"8.19","label":"v8.19.0","branchLabelMappingKey":"^v(\\d+).(\\d+).\\d+$","isSourceBranch":false,"state":"NOT_CREATED"}]}]
BACKPORT-->

Co-authored-by: José Luis González <[email protected]>
Co-authored-by: Elastic Machine <[email protected]>
akowalska622 pushed a commit to akowalska622/kibana that referenced this pull request May 29, 2025
…ils page (elastic#221350)

## Summary

Adding Test in Console and Delete from the Ruleset details page:



https://github.com/user-attachments/assets/e9db3752-a2e9-4a28-adac-0716809884d6


Test in Console example populating data from the ruleset selected:

![CleanShot 2025-05-23 at 12 18
35@2x](https://github.com/user-attachments/assets/fc94c0e0-f412-4193-9662-9a23703fbfcd)



### Checklist

Check the PR satisfies following conditions. 

Reviewers should verify this PR satisfies this list as well.

- [ ] Any text added follows [EUI's writing
guidelines](https://elastic.github.io/eui/#/guidelines/writing), uses
sentence case text and includes [i18n
support](https://github.com/elastic/kibana/blob/main/src/platform/packages/shared/kbn-i18n/README.md)
- [ ]
[Documentation](https://www.elastic.co/guide/en/kibana/master/development-documentation.html)
was added for features that require explanation or tutorials
- [ ] [Unit or functional
tests](https://www.elastic.co/guide/en/kibana/master/development-tests.html)
were updated or added to match the most common scenarios
- [ ] If a plugin configuration key changed, check if it needs to be
allowlisted in the cloud and added to the [docker
list](https://github.com/elastic/kibana/blob/main/src/dev/build/tasks/os_packages/docker_generator/resources/base/bin/kibana-docker)
- [ ] This was checked for breaking HTTP API changes, and any breaking
changes have been approved by the breaking-change committee. The
`release_note:breaking` label should be applied in these situations.
- [ ] [Flaky Test
Runner](https://ci-stats.kibana.dev/trigger_flaky_test_runner/1) was
used on any tests changed
- [ ] The PR description includes the appropriate Release Notes section,
and the correct `release_note:*` label is applied per the
[guidelines](https://www.elastic.co/guide/en/kibana/master/contributing.html#kibana-release-notes-process)

### Identify risks

Does this PR introduce any risks? For example, consider risks like hard
to test bugs, performance regression, potential of data loss.

Describe the risk, its severity, and mitigation for each identified
risk. Invite stakeholders and evaluate how to proceed before merging.

- [ ] [See some risk
examples](https://github.com/elastic/kibana/blob/main/RISK_MATRIX.mdx)
- [ ] ...

---------

Co-authored-by: Elastic Machine <[email protected]>
Co-authored-by: kibanamachine <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
backport:version Backport to applied version labels release_note:skip Skip the PR/issue when compiling release notes Team:Search v8.19.0 v9.1.0
Projects
None yet
Development

Successfully merging this pull request may close these issues.

4 participants